#include "memoryPool.h"

MemoryPool::MemoryPool()
{
    /* 大内存块 */
    m_blockHead = nullptr;
    /* 小内存块 */
    m_nodeHead = nullptr;
}

/* 分配空间 */
void *MemoryPool::AllocateNum()
{
    /* 没有多余空间 */
    if (m_nodeHead == nullptr)
    {
        Block *newBlock = new Block;
        /* 清理脏数据 */
        memset(newBlock, 0, sizeof(Block));

        for (int idx = 0; idx < NODECNT - 1; idx++)
        {
            newBlock->node[idx].next = &(newBlock->node[idx + 1]);
        }
        /* 最后一个小内存块需要单独处理. */
        newBlock->node[NODECNT - 1].next = nullptr;

        /* 头插 */
        newBlock->next = m_blockHead;
        m_blockHead = newBlock;

        /* 维护连接 */
        m_nodeHead = &(newBlock->node[0]);
    }

    auto ptr = m_nodeHead;
    /* 清除脏数据 */
    memset(ptr, 0, sizeof(UseNode));
    m_nodeHead = m_nodeHead->next;
    return ptr;
}

/* 释放空间 */
void MemoryPool::free(void *ptr)
{
    UseNode *node = static_cast<UseNode *>(ptr);
    /* 清除脏数据 */
    memset(ptr, 0, sizeof(UseNode));

    node->next = m_nodeHead;
    m_nodeHead = node;
}
/* 析构函数 */
MemoryPool::~MemoryPool()
{
    while (m_blockHead != nullptr)
    {
       Block* delBlock = m_blockHead;

       m_blockHead = m_blockHead->next;

       delete delBlock;
       delBlock = nullptr;
    }
}
